package com.snowfield.lb47.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.snowfield.lb47.lbconfig.domain.FrontProxy;

import java.util.*;

public class FrontProxyCache {
    private static final String FRONTPROXY_KEY = "frontproxy:";
    private static final String FRONTPROXY_SUMMARY_KEY = "frontproxySummary";

    /**
     * 设置前端代理缓存
     *
     * @param proxyList 前端代理列表
     */
    public static void setProxyCache(List<FrontProxy> proxyList) {
        for (FrontProxy proxy : proxyList) {
            Long proxyId = proxy.getId();
            SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(String.valueOf(proxyId)), proxy);
        }
    }

    /**
     * 设置前端代理缓存
     *
     * @param key   键
     * @param proxy 前端代理
     */
    public static void setProxyCache(String key, FrontProxy proxy) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), proxy);
    }

    /**
     * 根据KEY获取前端代理缓存
     *
     * @param key 键
     * @return objectCache 前端代理
     */
    public static JSONObject getProxyCache(String key) {
        JSONObject objectCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(objectCache)) {
            return objectCache;
        }
        return null;
    }

    /**
     * 删除指定前端代理缓存
     *
     * @param key 键
     */
    public static void removeProxyCache(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key));
    }

    /**
     * 清空前端代理缓存
     */
    public static void clearProxyCache() {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(FRONTPROXY_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);
    }

    /**
     * 设置cache key
     *
     * @param key 键
     * @return 缓存键key
     */
    public static String getCacheKey(String key) {
        return FRONTPROXY_KEY + key;
    }

    /**
     * 设置全部前端代理概要信息缓存
     *
     * @param proxySummary 全部前端代理概要信息
     */
    public static void setProxySummaryCache(Map<String, Map<String,String>> proxySummary) {
        SpringUtils.getBean(RedisCache.class).setCacheMap(FRONTPROXY_SUMMARY_KEY, proxySummary);
    }

    /**
     * 获取全部前端代理概要信息缓存
     *
     */
    public static Map<String, Map<String,String>> getProxySummaryCache() {
        Map<String, Map<String,String>> objectCache = SpringUtils.getBean(RedisCache.class).getCacheMap(FRONTPROXY_SUMMARY_KEY);
        if (StringUtils.isNotNull(objectCache)) {
            return objectCache;
        }
        return null;
    }

    /**
     * 删除全部前端代理概要信息缓存
     *
     */
    public static void removeProxySummaryCache() {
        SpringUtils.getBean(RedisCache.class).deleteObject(FRONTPROXY_SUMMARY_KEY);
    }
}
